<?php
class Tree{
 //原始的分类数据
private $rawList = array();
 //格式化后的分类
private $formatList = array();
 //格式化的字符
private $icon = array('│','├ ','└ ');
 //字段映射，分类id，上级分类pid,分类名称title,格式化后分类名称fulltitle
private $field = array();

/*
 * 功能：构造函数
* 属性：public
 * 参数： $field，字段映射，分类id，上级分类pid,分类名称title,格式化后分类名称fulltitle
 * 返回：无
*/
public function __construct($field = array()){
 $this->field['mid'] = isset($field['0']) ? $field['0'] : 'mid';
 $this->field['parent'] = isset($field['1']) ? $field['1'] : 'parent';
 $this->field['name'] = isset($field['2']) ? $field['2'] : 'name';
 $this->field['fulltitle'] = isset($field['3']) ? $field['3'] : 'fulltitle';
 // $this->field['odnum'] = isset($field['4']) ? $field['4'] : 'odnum';
 }

/*
 * 功能：返回给定上级分类$parent的所有同一级子分类
* 属性：public
 * 参数：上级分类$parent
 * 返回：子分类，二维数组
*/
public function getChild($parent, $data = array()){
 $childs = array();
 if(empty($data)) $data = $this->rawList;
 foreach($data as $Category){
 if($Category[$this->field['parent']]==$parent) $childs[]=$Category;
 }
 return $childs;
 }

/*
 * 功能：得到递归格式化分类
* 属性：public
 * 参数：$data，二维数组，起始分类id，默认$mid=0
 * 返回：递归格式化分类数组
*/
public function getTree($data, $mid = 0){
 if(empty($data)) return false; //数据为空，则返回
$this->rawList = array();
 $this->formatList = array();
 $this->rawList = $data;
 $this->_searchList($mid);
 return $this->formatList;
 }

/*
 * 功能：无限分类核心部分，递归格式化分类前的字符
* 属性：private
 * 参数：分类id，前导空格
* 返回：无
*/
private function _searchList($mid=0, $space = ""){
 //下级分类的数组
$childs = $this->getChild($mid);
 //如果没下级分类，结束递归
//如果在一个函数中调用 return() 语句，将立即结束此函数的执行并将它的参数作为函数的值返回
if(!($n = count($childs))) return;
 $cnt = 1;
 //循环所有的下级分类
for($i=0; $i<$n; $i++){
 $pre = "";
 $pad = "";
if($n==$cnt){
 $pre = $this->icon[2];
 }else{
 $pre = $this->icon[1];
 $pad = $space ? $this->icon[0] : "";
 }
 $childs[$i][$this->field['fulltitle']] = ($space ? $space.$pre : "").$childs[$i][$this->field['name']];
 $this->formatList[] = $childs[$i];
 //递归下一级分类
$this->_searchList($childs[$i][$this->field['mid']], $space.$pad."&nbsp;&nbsp;");
 $cnt++;
 }
 }
 
 }
 ?>
